package cn.dugcrs.basic.controller;

import cn.dugcrs.basic.utils.AjaxResult;
import cn.dugcrs.basic.utils.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    // 文件上传
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file", required = true) MultipartFile file) {
        try {
            String Filename = file.getOriginalFilename();
            String substring = Filename.substring(Filename.lastIndexOf(".") + 1);
            String resultPath = FastdfsUtil.upload(file.getBytes(), substring);
            return AjaxResult.success().setResultObj(resultPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    // 文件删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path", required = true) String path) {
        try {
            String pathTmp = path.substring(1);
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastdfsUtil.delete(groupName, remotePath);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

}
